package xkp.lesson7;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8888);
        //accept也有阻塞的情况，如果没有客户端到来，一直阻塞
        Socket socket =serverSocket.accept();
        //收发分离
        //2、子线程接收数据
        new Thread(){
            @Override
            public void run() {
                try {
                    DataInputStream inputStream = new DataInputStream(socket.getInputStream());
                    while(true) {
                        //此时I/O中的read会有阻塞的情况,如果没有数据到来，一直等待
                        String readStr = inputStream.readUTF();
                        System.out.println("接收到:" + readStr);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
        //1、主线程发送数据  获取系统输入然后发送
        Scanner scanner = new Scanner(System.in);
        DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
        while(true){
            String sendStr = scanner.nextLine();
            outputStream.writeUTF(sendStr);
            outputStream.flush();
        }


    }
}
